extends Node2D
signal played
signal closed
var children:Array[Sprite2D]
var open_progress:Array[float]
var _twn:Tween
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	var c=get_children()
	for ch in c:
		if ch is Sprite2D:children.push_back(ch)
	for child in children:
		open_progress.push_back(child.material.get_shader_parameter("y_scale"))
	self.visible=false

func play()->void:
	if _twn:
		if _twn.is_running():
			return
	for child in children:
		child.material.set_shader_parameter("y_scale",0.0)
	_twn=create_tween()
	_twn.tween_property(self,"visible",true,0.1)
	for i in children.size():
		_twn.parallel().tween_property(children[i].material,"shader_parameter/y_scale",open_progress[i],0.5)
	_twn.tween_property(self,"visible",true,0.5)
	for i in 3:
		for child in children:
			_twn.parallel().tween_property(child.material,"shader_parameter/eye_offset_x",randf_range(-0.5,0.5),0.2).set_trans(Tween.TRANS_CIRC).set_ease(Tween.EASE_IN)
			_twn.parallel().tween_property(child.material,"shader_parameter/eye_offset_y",randf_range(-0.5,0.5),0.2).set_trans(Tween.TRANS_CIRC).set_ease(Tween.EASE_IN)
		_twn.tween_property(self,"visible",true,0.7)
	var targetpos:Vector2=Vector2(0,-300)
	for child in children:
		var dir:Vector2 = (targetpos-child.position).normalized()/2.5
		dir=dir.rotated(-child.rotation)
		_twn.parallel().tween_property(child.material,"shader_parameter/eye_offset_x",dir.x,0.2)
		_twn.parallel().tween_property(child.material,"shader_parameter/eye_offset_y",dir.y,0.2)
	_twn.tween_callback(played.emit)
	_twn.tween_property(self,"visible",true,2)
				
func close()->void:
	if _twn:
		if _twn.is_running():
			await _twn.finished
	_twn=create_tween()
	_twn.tween_property(self,"visible",true,0.1)
	for i in children.size():
		_twn.parallel().tween_property(children[i].material,"shader_parameter/y_scale",0.0,0.5)
	_twn.tween_property(self,"visible",false,0.1)
	_twn.tween_callback(closed.emit)
